import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/util/ext_utils.dart';

import '../a_yyt/models/floor_list_entity.dart';
import '../a_yyt/models/medical_elder_entity.dart';
import '../model/building_model.dart';
import '../model/customer_info_model.dart';
import '../net/api/http_api.dart';
class ChooseMultiElderViewModel extends BaseListViewModel<MedicalElderInfo> {
  ChooseMultiElderViewModel(BuildContext context,
      {List<MedicalElderInfo>? filterOld}) : super(context){
    if(filterOld!=null){
      chooseElders.addAll(filterOld);
    }
  }

  var buildingModel = BuildingModel();
  List<FloorEntity> buildingList = [];
  FloorEntity? selectBuilding;
  List<FloorInfo> floorList = [];
  FloorInfo? selectFloor;

  var chooseElders = <MedicalElderInfo>[];

  var searchName = "";

  var customerModel = CustomerInfoModel();

  @override
  Future<List<MedicalElderInfo>> requestListData() async {
    if (buildingList.isEmpty) {
      await _getBuildingData();
    }
    var list = await getOldData();
    return list;
  }

  Future<void> _getBuildingData() async {
    try {
      var list = await buildingModel.getBuildingList();
      if (list.isNotEmpty) {
        buildingList = list;
        buildingList.insert(0, FloorEntity(buildingNo: '全部',floorList: [FloorInfo(floorNo: '全部',isSelected: true)]));
      }
      selectBuilding = list[0];
      selectBuilding?.iSelected = true;
      // setFloor();
      requestRefresh();
      // await getOldData();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  void setFloor() {
    if (selectBuilding != null) {
      floorList = selectBuilding?.copy().floorList??[];

      if (floorList.first.floorNo != '全部') {
        var first = FloorInfo(
          floorNo: "全部",
        );
        first.iSelected = true;
        floorList.insert(0, first);
        selectFloor = first;
      } else {
        for (var item in floorList) {
          item.isSelected = false;
        }
        floorList.first.isSelected = true;
        selectFloor = floorList.first;
      }
    }
  }

  var inProcess = false;

  Future<List<MedicalElderInfo>> getOldData() async {
    var map = {
      'page': page,
      'rows': pageLength,
      // 'serviceAreaId': widget.serviceAreaId,
      'customerNameOrRoomNoLike': searchName,
      'orderBy': 'room_no',
      'orderByDesc': false, //不传或为false时是正序，传true时是倒序
      // 'isLive': '1'
      "statusMasterId":"0"
    };

    if (!(selectBuilding?.iId??"").isNullOrEmpty()) {
      map['buildingId'] = selectBuilding!.iId;
    }
    if (!(selectFloor?.iId??"").isNullOrEmpty()) {
      map['floorId'] = selectFloor!.iId;
    }

    var url = HttpApi.customerElder;
    var data =
    await HttpGo.instance.postData('${url}', data: map,options: PostRequest.urlencodedHeader);

    if (data['code'] == "0") {
      MedicalElderModel model = MedicalElderModel.fromJson(data['data']);
      return model.rows??[];
    } else {
      throw data['msg'];
    }
  }


  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }

  void allClick(){
    chooseElders.removeWhere((e)=>listItems.contains(e));
    chooseElders.addAll(listItems);
    notifyListeners();
  }

  void cancelCall(){
    chooseElders.removeWhere((e)=>listItems.contains(e));
    notifyListeners();
  }

  void clear(){
    chooseElders.clear();
    notifyListeners();
  }

  bool get isAllChoose{
    var isAll = true;
    if(listItems.isEmpty){
      isAll = false;
    }else{
      for(var item in listItems){
        if(!chooseElders.contains(item)){
          isAll = false;
          break;
        }
      }
    }
    return isAll;
  }

  void sortListByBuilding(){
    chooseElders.sort((o1,o2){
      return (o1.buildingNo??"").compareTo(o2.buildingNo??"");
    });
  }

  void showSelectSheet(){
    sortListByBuilding();
    showModalBottomSheet(context: context, builder: (context){
      return Column(
        children: [
          Row(
            children: [
              SizedBox(width: 16,),
              CommonText('已选长者',fontWeight: FontWeight.bold,textSize: 18).setWeight(1),
              CommonText("清空",textColor: Colors.blue).onTap((){
                clear();
                Go().pop();
              }),
              SizedBox(width: 16,)
            ],
          ),
          SizedBox(height: 15,),
          ListView.separated(itemBuilder: (context,index){
            var item = chooseElders[index];
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                if(index==0||(item.buildingNo!=chooseElders[index-1].buildingNo))
                CommonText(item.buildingNo).addToContainer(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(horizontal: 16,vertical: 8),
                  color: Color(0xffeeeeee)
                ),
                CommonText(item.name).addToContainer(
                  padding: EdgeInsets.symmetric(horizontal: 16,vertical: 8)
                )
              ],
            );
          }, separatorBuilder: (context,index){
            return Container();
          }, itemCount: chooseElders.length).setWeight(1)
        ],
      ).addToContainer(
        constraints: BoxConstraints(
          maxHeight: context.screenSize.height*0.75
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: 20.radius)
        ),
        padding: EdgeInsets.symmetric(vertical: 15)
      );
    },backgroundColor: Colors.transparent,isScrollControlled: true,);
  }
}
